/*
* Created on Tue Jun 13 2023 by Admin
*
* Copyright (c) 2023 shuangdi
*
* description: index
*
* date: 2024/10/23
*/
<template>
  <div class="root_graph" ref="graphDom"></div>
</template>

<script setup>
import {onBeforeUnmount, ref} from 'vue'
import {initGraph as graphMethod} from "./config/main"
import {handleData} from './config/handleData'

const graphDom = ref(null)
let graphExample = null
let currentTab = 'a'

//初始化图谱
async function initGraph(params) {
  const {optionsConfig, data} = handleData(params)
  if (graphExample) {
    graphExample?.clear()
    graphExample?.destroy()
    removeEvent()
  }
  const options = {
    data,
    optionsConfig,
    container: graphDom.value,
    width: graphDom.value.clientWidth,
    height: graphDom.value.clientHeight,
  }
  const graphClass = new graphMethod(options)
  graphClass.initGraph((graph) => {
    graphExample = graph
    addResizeEvent()
    // setEdgeColor()
  })
}


//添加自适应事件
function addResizeEvent() {
  // 监听全屏事件
  window.addEventListener('resize', handleFullscreenChange)
}

// 移除自适应事件
function removeEvent() {
  window.removeEventListener('resize', handleFullscreenChange)
}


// 检测屏幕自适应事件
function handleFullscreenChange() {
  const width = graphDom.value.clientWidth
  const height = graphDom.value.clientHeight
  graphExample.setSize(width, height)
  graphExample.resize()
  graphExample.fitView({direction: "both"}, false)
}

// 销毁图谱
function destroyGraph() {
  if (graphExample) {
    graphExample?.clear()
    graphExample?.destroy()
    graphExample = null
    removeEvent()
  }
}

let timer = null

// 重置线条颜色
function resetEdgeColor() {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  let data = graphExample.getEdgeData()
  data.forEach(item => {
    graphExample.updateEdgeData([
      {
        id: item.id,
        style: {
          stroke: 'transparent'
        }
      }
    ])
  })
  setTimeout(() => graphExample.draw(), 20)
}

// 设置线条颜色
function setEdgeColor() {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  let data = graphExample.getEdgeData()
  if (currentTab === 'a') {
    data = data.filter(v => v.style.visibility !== 'hidden')
  }
  let index = 0
  timer = setInterval(() => {
    if (index > (data.length - 1)) {
      clearInterval(timer)
      return
    }
    graphExample.updateEdgeData([{
      id: data[index].id,
      style: {
        stroke: '#ffffff'
      }
    }])
    graphExample.draw()
    index++
  }, 800)
}

// 组件销毁前
onBeforeUnmount(() => {
  destroyGraph()
  if (timer) {
    clearInterval(timer)
    timer = null
  }
})


defineExpose({initGraph, destroyGraph, setEdgeColor})
</script>

<style scoped lang="less">
.root_graph {
  width: 100%;
  height: 100%;
  position: relative;
}
</style>
